import process from 'child_process';
import uuid from 'node-uuid';
let androidDevices = []
let i = 1;
function devices() {
    process.exec("adb devices",function (error, stdout, stderr) {
        // console.log(error);
        if(error){
            console.error(stderr)
            return;
        }
        console.log(stdout)
        androidDevices =  stdout.trim().split("\r\n").splice(1,1).map(item =>{
            let obj = {};
            let line = item.split("\t");
            obj.deviceId = line[0];
            return obj;
        })
        console.log("当前设备：",androidDevices)
    })
}

function screencap(sid,pngPath,success) {
    process.exec("adb -s "+sid+" shell screencap -p /sdcard/"+pngPath,function (error, stdout, stderr) {
        if(error){
            console.error(stderr)
            return;
        }
        console.log(stdout)
        success()
    })
}

function pullPng(sid,pngPath,success) {
    process.exec("adb -s "+sid+" pull /sdcard/"+pngPath+" ./"+pngPath,function (error, stdout, stderr) {
        if(error){
            console.error(stderr)
            return;
        }
        console.log(stdout)
        success();
    })
}

function rmFile(sid,pngPath) {
    process.exec("adb -s "+sid+" shell rm -rf /sdcard/"+pngPath,function (error, stdout, stderr) {
        if(error){
            console.error(stderr)
            return;
        }
        console.log(stdout)

    })
}

//启动群控
function start() {
    //3秒一次扫描设备
    setInterval(function () {
        devices();
    }, 3000)

    setInterval(function () {
        let no = uuid.v1();
        androidDevices.forEach(item =>{
            let pngPath =  item.deviceId+"_"+no+".png";
            screencap(item.deviceId,pngPath,function () {
                pullPng(item.deviceId,pngPath,function () {
                    //刪除圖片
                    rmFile(item.deviceId,pngPath)
                    //调用大漠插件
                    console.log(item, "调用插件")
                })
            })
        })
    },1000 / 2); //每秒执行25次数，达到视觉无感知
}

start();//调用开始